// 导入数据库API
const db = require("../../config/db");
// 导入加密/解密文件
const aes2 = require("../../utils/aes2");
// 导入jwt token工具
const JwtUtil = require("../../utils/jwt");

// 正在表达式
const rep_phone = /^1[3-9]\d{9}$/;
const rep_email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
// 默认头像 , 例如： http://localhost:3000/imgs/1.jpg
let { HOST_URL } = require("../../config/host");
let user_avators = ["/images/1.jpg", "/images/2.jpg", "/images/3.jpg", "/images/4.jpg", "/images/5.jpg", "/images/6.jpg"];

let rd = () => {
    return Math.floor(Math.random() * user_avators.length);
};

// 封装注册接口
// const register = (user_id, user_acc, user_pwd, user_nick_name) => {
const register = (user_id, user_acc, user_pwd, user_nick_name, user_create_time) => {
    return new Promise((resolve, reject) => {
        let user_check_sql = `select * from db_user where user_acc = "${user_acc}"`;
        db.query(user_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: "查询用户异常。",
                });
            } else {
                // result: 数组
                // result.length == 0 该账号还没被注册
                // console.log("4.0",{user_id, user_acc, user_pwd, user_nick_name, user_create_time});
                if (result.length == 0) {
                    let pwd = aes2.aesEncrypt(user_pwd); //加密
                    let avator = HOST_URL + user_avators[rd()]; // 用户默认头像
                    let user_insert_sql = `insert into db_user(user_id,user_acc,user_pwd,user_nick_name,user_create_time,user_avator) values("${user_id}","${user_acc}","${pwd}","${user_nick_name}","${user_create_time}","${avator}")`;
                    db.query(user_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: "用户注册失败。",
                                err,
                            });
                        } else {
                            resolve({
                                code: 200,
                                msg: "用户注册成功。",
                                user_nick_name,
                            });
                        }
                    });
                } else {
                    resolve({
                        code: 201,
                        msg: "该账号已经存在。",
                    });
                }
            }
        });
    });
};

// 封装用户登录接口
// 设置用户登录的有效时间
// 把用户的user_id生产临时的随机字符串(token)
// token: 临时身份（令牌）
const login = (user_acc, user_pwd) => {
    return new Promise((resolve, reject) => {
        // 查询用户表sql语句
        let user_check_sql = "";
        // 判断用户输入的是邮箱还是手机
        if (rep_email.test(user_acc)) {
            user_check_sql = `select * from db_user where user_acc="${user_acc}"`;
        } else if (rep_phone.test(user_acc)) {
            user_check_sql = `select * from db_user where user_phone="${user_acc}"`;
        }
        // console.log("6.0", user_acc, user_pwd);
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                resolve({
                    code: -1,
                    msg: "账号或密码错误。",
                });
            } else {
                if (rows.length == 1) {
                    // 匹配密码
                    // 参数1：前端提交的密码，参数2：数据库的密码
                    // console.log('7.0', aes2.aesDecrypt(user_pwd, rows[0]['user_pwd']));
                    if (aes2.aesDecrypt(user_pwd, rows[0]["user_pwd"])) {
                        let [{ user_id, user_nick_name, user_acc, user_phone, user_avator }] = rows;
                        // 将用户id传入并生成token
                        let jwt = new JwtUtil(user_id);
                        // 获取token
                        let token = jwt.generateToken();
                        // 定义用户对象
                        let user = {
                            code: 200,
                            msg: "恭喜您,登录成功。",
                            token,
                            user_id,
                            user_nick_name,
                            user_acc,
                            user_avator,
                        };
                        if (user_phone) {
                            user["user_phone"] = user_phone;
                        }
                        // 将 token 等信息反馈给客户端
                        resolve(user);
                    } else {
                        resolve({
                            code: -1,
                            msg: "账号或密码错误1",
                        });
                    }
                } else if (rows.length == 0) {
                    resolve({
                        code: -1,
                        msg: "账号不存在。",
                    });
                } else {
                    resolve({
                        code: 500,
                        msg: "系统异常。",
                    });
                }
            }
        });
    });
};

module.exports = {
    //注册接口
    register(user_id, user_acc, user_pwd, user_nick_name, user_create_time, email_code) {
        // 需要用邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    console.log("邮箱验证码查询失败:", err);
                    reject({
                        code: -1,
                        msg: "邮箱验证码查询失败。",
                    });
                } else {
                    console.log("rows:", rows);
                    // console.log("length:",rows.length)
                    if (rows.length == 1) {
                        // 注册用户账号
                        register(user_id, user_acc, user_pwd, user_nick_name, user_create_time)
                            .then((res) => {
                                resolve(res);
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        resolve({
                            code: -1,
                            msg: "邮箱验证码查询异常,请重新发送验证码。",
                        });
                    }
                }
            });
        });
    },

    //登录接口
    login(user_acc, user_pwd, email_code) {
        // 需要邮箱验证码
        return new Promise((resolve, reject) => {
            let vercode_sql = `select v1 from db_code where v1="${email_code}"`;
            db.query(vercode_sql, (err, rows) => {
                if (err) {
                    // console.log("邮箱验证码查询失败:",err);
                    reject({
                        code: -1,
                        msg: "邮箱验证码查询失败。",
                    });
                } else {
                    if (rows.length == 1) {
                        // 用户账号登录
                        login(user_acc, user_pwd)
                            .then((res) => {
                                resolve(res);
                            })
                            .catch((err) => {
                                reject(err);
                            });
                    } else {
                        resolve({
                            code: -1,
                            msg: "邮箱验证码查询异常,请重新发送验证码。",
                        });
                    }
                }
            });
        });
    },

    // 修改用户头像（上传图片）
    modify_avator(user_id, user_avator) {
        // console.log({user_id, user_avator});
        return new Promise((resolve, reject) => {
            let usr_check_sql = `select * from db_user where user_id = "${user_id}"`;
            db.query(usr_check_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "查询用户失败",
                        err,
                    });
                } else {
                    if (rows.length == 1) {
                        let user_modify_sql = `update db_user set user_avator= "${user_avator}" where user_id= "${user_id}"`;
                        db.query(user_modify_sql, (error, result) => {
                            console.log("9.0", { user_id, user_avator, error });
                            if (error) {
                                reject({
                                    code: -1,
                                    msg: "修改用户头像失败。",
                                    error,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改用户头像成功。",
                                    user_avator,
                                });
                            }
                        });
                    }
                }
            });
        });
    },

    // 获取用户头像和昵称
    get_avator_nickname(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select user_avator,user_nick_name from db_user where user_id = "${user_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "获取头像昵称失败。",
                    });
                } else {
                    reject({
                        code: 200,
                        msg: "获取头像昵称成功。",
                        data: rows,
                    });
                }
            });
        });
    },

    // 修改用户资料
    modify(user_id, user_age, user_addr, user_phone, user_sex, user_nick_name) {
        return new Promise((resolve, reject) => {
            var modify_info_sql = `update db_user set user_addr= "${user_addr}", user_age= "${user_age}", user_phone= "${user_phone}",user_sex= "${user_sex}",user_nick_name= "${user_nick_name}" where  user_id= "${user_id}"`;
            db.query(modify_info_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "修改用户资料失败。",
                        err,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "修改用户资料成功。",
                    });
                }
            });
        });
    },

    // 删除账号
    remove(user_id, user_acc) {
        return new Promise((resolve, reject) => {
            let user_check_sql = `select user_acc from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
            db.query(user_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        err,
                    });
                } else {
                    if (result.length == 1) {
                        let user_remove_sql = `delete from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
                        db.query(user_remove_sql, (err, rows) => {
                            if (err) {
                                reject({
                                    code: -1,
                                    msg: "删除用户失败1。",
                                    err,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "删除用户成功。",
                                });
                            }
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "删除用户失败2。",
                            err,
                        });
                    }
                }
            });
        });
    },
    // 查询账号详情
    detail(user_id, user_acc) {
        return new Promise((resolve, reject) => {
            let user_check_sql = `select user_acc,user_age,user_sex,user_avator,user_create_time from  db_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
            db.query(user_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        err,
                    });
                } else {
                    if (result.length == 1) {
                        resolve({
                            code: 200,
                            msg: "查询用户详情成功。",
                            data: result[0],
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "查询用户详情失败。",
                            err,
                        });
                    }
                }
            });
        });
    },

    //查看浏览记录
    look(gids) {
        return new Promise((resolve, reject) => {
            let check_look_sql = `select * from db_goods where FIND_IN_SET(gid,'${gids}')`;
            db.query(check_look_sql, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    },

    modify_name(user_nick_name, user_id) {
        return new Promise((resolve, reject) => {
            let modify_name_sql = `update db_user set user_nick_name="${user_nick_name}" where user_id="${user_id}"`;
            db.query(modify_name_sql, (err, rows) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    },
};
